package java_NIO;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class demo_01_Channel {
    public static void main(String[] args) throws IOException {
        // 使用随机流读写文件
        RandomAccessFile aFile = new RandomAccessFile("C:\\Users\\Administrator\\Desktop\\123.txt", "rw");
        FileChannel inChannel = aFile.getChannel();

        ByteBuffer buf = ByteBuffer.allocate(48); // nio的buffer
        int bytesRead = inChannel.read(buf); // 初始化写入到buffer
        while (bytesRead != -1) {
            System.out.println("Read " + bytesRead);
            buf.flip(); // 切换读写模式

            while(buf.hasRemaining()){
                System.out.print((char) buf.get()); // 读取buff的内容
            }
            buf.clear();  // buffer清空，使之可以再次写入
            bytesRead = inChannel.read(buf); // 写入到buffer

        }

        buf.put((byte)12);
        inChannel.write(buf);

        aFile.close();
    }
}
